package com.zwy.Shopping.servlet_;

import com.zwy.Shopping.dao.ProductDao;
import com.zwy.Shopping.dao.impl.ProductDaoImpl;
import com.zwy.Shopping.model.CartItem;
import com.zwy.Shopping.model.Product;
import com.zwy.Shopping.model.User;
import org.apache.jasper.tagplugins.jstl.core.Out;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.List;

import static java.lang.System.out;

@WebServlet("/add_shopping_car")
public class AddShoppingCarServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //获取已有的购物车商品
        ServletContext application = this.getServletContext();
        List<CartItem> cartItemList = (List<CartItem>) application.getAttribute("cartItemList");
        //index.jsp/addShoppingCar方法传过来的productId
      String productIdStr = request.getParameter("productId");
        User user = (User)request.getSession().getAttribute("user");
        if(user == null){
           out.print("登陆后加入购物车");
        }else{
        ProductDao productDao = new ProductDaoImpl();
        if(productIdStr == null){
            out.println("没有获取到商品id");
        }
        try {
           int productId = Integer.parseInt(productIdStr);
            Product product = productDao.getProductById(productId);
            //实例化一个CartItem对象然后对其初始化
            CartItem cartItem = new CartItem();
            cartItem.setProduct(product);
            cartItem.setQuantity(1);
            cartItem.setUserId(user.getId());
            //将其添加到cartItemList集合里
            cartItemList.add(cartItem);
            //更新application域对象cartItemList的数据
            application.setAttribute("cartItemList",cartItemList);
            //获取application域对象cartItemNum(购物车商品行数)
            int cartItemNum =(Integer) application.getAttribute("cartItemNum");
            cartItemNum++;
            //更新
            application.setAttribute("cartItemNum",cartItemNum);


        }catch (Exception e){
            e.printStackTrace();
        }
    }
    }
}
